#!/usr/bin/env python
# -*- coding: utf-8 -*-

import csv
import os


class Field(object):
    def __init__(self, id,
                 name=None,
                 valueType=None,
                 unit=None,
                 intervals=None,
                 isIdField=False,
                 description=None,
                 **kwargs):
        self.id = id if id != 'id' else 'legacyDBId'
        self.name = name if name else self.id

        self.valueType = valueType
        self.unit = unit if unit else ''
        self.description = description if description else ''
        self.intervals = intervals if intervals else []
        self.isIdField = isIdField

    def update_name(self, name):
        if name:
            self.name = name


class MetaDataDT040(object):
    def __init__(self, id=None,
                 name=None,
                 description=None,
                 sensors=None,
                 attributes=None,
                 tags=None,
                 **kwargs):
        self.id = id
        self.name = name
        self.fields = []
        self.description = description if description else ''
        self.attributes = attributes if attributes else []
        self.tags = tags if tags else []

        # self.initial_field(sensors)

    def add_tag(self, tag=''):
        self.tags.append(tag)

    def initial_field(self, sensors):
        _dict = {}
        csvreader = csv.DictReader(open(os.path.join(os.path.dirname(__file__), 'SensorMapping.csv')),
                                   fieldnames=["SensorId", "SensorName"])
        for line in csvreader:
            _dict.update({line['SensorId']: line['SensorName']})
        for sensor in sensors:
            s = Field(**sensor)
            s.name = _dict.get(s.id)
            self.add_idfield(**s.__dict__)

    def add_idfield(self, **kwargs):
        sensor = Field(**kwargs)
        self.fields.append(sensor.__dict__)

        # def optimize_fields(self):
        #     for field in self.fields:
        #         sensor = Sensor(**field)
        #         if sensor.id == 'id':
        #             sensor.id = 'legacyDBId'
        #             self.fields.remove(field)
        #
